package com.mju.config;

import java.io.IOException;
import java.time.Duration;
import java.util.HashMap;
import java.util.Map;

import org.json.JSONObject;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.beans.factory.annotation.Value;
import org.springframework.data.redis.core.RedisTemplate;
import org.springframework.security.core.Authentication;
import org.springframework.security.web.authentication.AuthenticationSuccessHandler;
import org.springframework.stereotype.Component;

import com.fasterxml.jackson.databind.ObjectMapper;
import com.mju.model.dto.SecurityUser;
import com.mju.model.dto.UserInfo;
import com.mju.utils.JWTUtils;

import jakarta.servlet.ServletException;
import jakarta.servlet.http.HttpServletRequest;
import jakarta.servlet.http.HttpServletResponse;
import lombok.extern.slf4j.Slf4j;

@Slf4j
@Component
public class AuthSuccessHandler implements AuthenticationSuccessHandler{
	
	@Autowired
	private RedisTemplate redisTemplate;
	
	@Value("${custom.userExpired}")
	private int userExpired;
	@Value("${custom.userRedisKey}")
	private String userRedisKey;
		
	@SuppressWarnings("unchecked")
	@Override
	public void onAuthenticationSuccess(HttpServletRequest req, HttpServletResponse resp,
			Authentication auth) throws IOException, ServletException {
			resp.setContentType("application/json;charset=utf-8");
			Map<String, Object> respData = new HashMap<>();
			respData.put("code", 0);
			respData.put("msg", "登录成功");
			respData.put("count", 1);
			SecurityUser user = (SecurityUser) auth.getPrincipal();
			UserInfo userInfo = user.getUserInfo();
			userInfo.setPasswd(null);// 数据脱敏
			respData.put("data", userInfo);
			JSONObject json = (JSONObject) JSONObject.wrap(respData);

			//把对象转换为Map,为了保存在redis中
			ObjectMapper m=new ObjectMapper();
			Map<String,String> redisMap=new HashMap<>();
			redisMap=m.convertValue(userInfo, Map.class);

			//把用户信息数据记录到redis中
			String redisKey=userRedisKey+userInfo.getStudentno();
			redisTemplate.opsForHash().putAll(redisKey, redisMap); 
			redisTemplate.expire(redisKey,Duration.ofDays(userExpired));
			
			// 生成token
			JSONObject userInfoJSON = (JSONObject) JSONObject.wrap(userInfo);
			String jwt = JWTUtils.genToken(userInfoJSON.toString());
			resp.setHeader("Authorization", "Bearer " + jwt);
			resp.getWriter().write(json.toString());
	}

}
